﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TjZheng.SSO.Process;
using TjZheng.Framework;
using System.Text;

namespace TjZheng.SSO.Web.Filter
{
    [BenzAuthFilter(SSOPowerType.CheckLogin)]
    public class BenzController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [BenzAuthFilter(SSOPowerType.None)]
        public ActionResult Target(string targetUrl, string userId, string ticket)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (targetUrl.IsNull())
            {
                objInvokeResult.ResultCode = "TargetUrlNull";
                objInvokeResult.ResultMessage = "跳转地址为空";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            if (userId.IsNull())
            {
                objInvokeResult.ResultCode = "UserIdNull";
                objInvokeResult.ResultMessage = "用户Id为空";
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            //todo：验证密钥和双方约定的token
            objInvokeResult = Request.Url.AbsoluteUri.ToString().CheckUrlSignature();
            if (objInvokeResult.ResultCode != "Success")
            {
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }
            objInvokeResult = ("http://tjzheng.sso.com/api/ssoapi/" + userId).CreateHttpGet<InvokeResult>();
            if (objInvokeResult.ResultCode != "Success")
            {
                return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
            }

            CookieHelper.SetCookieValue(userId, "UserId");
            return Redirect(targetUrl);
        }

        [BenzAuthFilter(SSOPowerType.None)]
        public ActionResult LoginOut()
        {
            string userId = CookieHelper.GetCookieValue("UserId");
            var objHttpWebRequest = ("http://tjzheng.sso.com/api/ssoapi/" + userId).CreateHttpRequest();
            objHttpWebRequest.Method = "Delete";
            InvokeResult objInvokeResult = objHttpWebRequest.GetHttpResponse(Encoding.UTF8).JsonDeserialize<InvokeResult>();
            if (objInvokeResult.ResultCode == "Success")
            {
                CookieHelper.RemoveCookie("UserId");
            }
            return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AjaxData()
        {
            InvokeResult objInvokeResult = new InvokeResult();
            return Json(objInvokeResult, JsonRequestBehavior.AllowGet);
        }
    }
}
